/*
Author: Surpass-HC
Source: https://gitee.com/hxchuan000/clpc-1
Mail: surpass-hc@qq.com
*/
#include <lxFileOpt.h>

int fileOptSelect(int fd, time_t timeoutMs)
{
    fd_set rset;
    struct timeval tv;
    int maxSockfd = 0;
    int rc = 0;
    tv.tv_sec = timeoutMs / 1000;
    tv.tv_usec = timeoutMs % 1000 * 1000;
    FD_ZERO(&rset);
    if (fd < 0)
    {
        printf("file select fd error\n");
        return -1;
    }
    FD_SET(fd, &rset);
    maxSockfd = fd + 1;
    rc = select(maxSockfd, &rset, NULL, NULL, &tv);
    if (rc < 0)
    {
        printf("file select result error\n");
        return -2;
    }
    if (rc == 0)
    {
        return 0;
    }
    if (!FD_ISSET(fd, &rset))
    {
        return 0;
    }
    return 1;
}

int fileReadWithTime(int fd, char *outStr, int readSize, time_t timeoutMs)
{
    int tmpflag = 0;
    if (!outStr)
    {
        printf("read by time out str ptr error\n");
        return -1;
    }
    tmpflag = fileOptSelect(fd, timeoutMs);
    if (tmpflag <= 0)
    {
        return tmpflag;
    }
    tmpflag = read(fd, outStr, readSize);
    return tmpflag;
}

int fileCfgNoBlock(int fd)
{
    int tmpflag = fcntl(fd, F_GETFL);
    tmpflag |= O_NONBLOCK;
    if (fcntl(fd, F_SETFL, tmpflag) < 0)
    {
        printf("set no block socket error:%d\n", fd);
        return -1;
    }
    return 0;
}
